package com.itjiange.controller;

import com.itjiange.pojo.UserRegisterDto;
import com.itjiange.service.UserService;
import com.itjiange.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 用户注册
 *
 * @author ItJiange
 * @date 2023/10/16
 */
@WebServlet("/user/register")
public class UserRegisterController extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 0. 设置编码格式
        req.setCharacterEncoding("utf-8");
        // 1. 获取请求参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 2. 封装 UserDto 对象
        UserRegisterDto userRegisterDto = new UserRegisterDto();
        userRegisterDto.setUsername(parameterMap.get("username")[0]);
        userRegisterDto.setUserPassword(parameterMap.get("userPassword")[0]);
        userRegisterDto.setRepeatPassword(parameterMap.get("repeatPassword")[0]);
        userRegisterDto.setEmailAddress(parameterMap.get("emailAddress")[0]);
        userRegisterDto.setHobby(parameterMap.get("hobby")[0]);

        boolean flag = userService.userRegister(userRegisterDto);
        if (flag) {
            System.out.println("注册成功");
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        }
        System.out.println("注册失败");
        resp.sendRedirect(req.getContextPath() + "/error.html");
    }
}
